import React, { useRef } from 'react';
import { Modal, Button, Space, Input, Form, Radio, Select, Cascader, Switch, message } from 'antd';
import { useMemo, useState, useEffect } from 'react';
import TagInput from '@/components/inputs/TagInput';

import { SvgIcon } from '@/components/icon';
import { CloseOutlined, InfoCircleOutlined } from '@ant-design/icons';
import useWindowWidth from '@/hooks/event/use-window-width';
import { useTranslation } from 'react-i18next';
import { TextArea } from 'antd-mobile';
import { none } from 'ramda';
import Modals from '@/components/modals/Modals';
import { validateAndConvertValue } from './NewApiModal';

interface DeleteConfirmModalProps {
  visible: boolean;
  onCancel: () => void;
  onConfirm: (onItem: any) => void;
  onItem?: any;
  title: string;
  isErr: string;
}

interface Option {
  key: string;
  value: string | number;
  label: React.ReactNode;
  name: string;
  children?: Option[];
}

const connectorAddModal: React.FC<DeleteConfirmModalProps> = ({
  visible,
  onCancel,
  onConfirm,
  onItem,
  title,
  isErr,
}) => {
  const { t } = useTranslation();
  const { isPc } = useWindowWidth();

  const [form] = Form.useForm();
  const scrollContainerRef = useRef<HTMLDivElement>(null);

  const [formBaseValue, setFormBaseValue] = useState({
    properties: {
      list: [
        {
          first: '',
          second: '',
          third: '',
          fourth: '',
          fifth: '',
        },
      ],
    },
  });

  console.log('dhaksjdhaksl', onItem);

  useEffect(() => {
    // setFormBaseValue(onItem);
    console.log('onItem=============', onItem);
    form.setFieldsValue(onItem);
  }, [onItem]);

  const handleAdd = (subOpt: any) => {
    subOpt.add({
      first: '', // 参数名称
      second: '', // 参数说明
      third: 'string', // 参数类型，默认为 string
      fourth: '是', // 必须字段，默认为否
      fifth: [], // 示例值数组，默认为空数组
      enum: [], // 示例值数组，默认为空数组
    });
    // 延迟执行滚动保证DOM更新完成
    setTimeout(() => {
      if (scrollContainerRef.current) {
        scrollContainerRef.current.scrollTop = scrollContainerRef.current.scrollHeight;
      }
    }, 0);
  };

  return (
    <Modals
      open={visible}
      onCancel={onCancel}
      width={712}
      className="model-css"
      title={
        <div>
          {title}
        </div>
      }
      onOk={async () => {
        try {
          const values = await form.validateFields();
          // 校验所有参数的示例值
          const list = values.properties.list;
          let hasInvalidValue = false;
          let errorMessage = '';

          for (let i = 0; i < list.length; i++) {
            const item = list[i];
            const type = item.third;
            const enumValues = item.enum || [];

            // 跳过 array 和 object 类型的校验
            if ((type === 'array' || type === 'object') && enumValues.length > 0) {
              hasInvalidValue = true;
              errorMessage = `${type} 类型不支持示例值配置`;
              break;
            }

            // 校验每个示例值
            for (const value of enumValues) {
              const { isValid } = validateAndConvertValue(type, String(value));
              if (!isValid) {
                hasInvalidValue = true;
                errorMessage = `参数 "${item.first}" 的示例值 "${value}" 不符合类型 ${type}`;
                break;
              }
            }

            if (hasInvalidValue) {
              break;
            }



          }

          if (hasInvalidValue) {
            message.warning(errorMessage);
            return;
          }

          onConfirm(values);
        } catch (errorInfo) {
          console.error('Validation failed:', errorInfo);
        }
      }}
    // footer={
    //   <div style={{ textAlign: 'center' }}>
    //     <Space size={10}>
    //       <Button size="large" shape="round" onClick={onCancel}>
    //         {'取消'}
    //       </Button>
    //       <Button
    //         size="large"
    //         shape="round"
    //         type="primary"
    //         onClick={async () => {
    //           try {
    //             const values = await form.validateFields();
    //             console.log('values============', values);

    //             onConfirm(values);
    //           } catch (errorInfo) {
    //             console.error('Validation failed:', errorInfo);
    //           }
    //         }}
    //       >
    //         {'确认'}
    //       </Button>
    //     </Space>
    //   </div>
    // }
    >
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          margin: '0px 0px',
        }}
      >
        <Form
          initialValues={formBaseValue}
          form={form}
          layout="vertical"
          className="form-item-space"
        >
          <Form.Item
            className="form-icon-color"
            label="接口名称"
            name="name"
            style={{ marginTop: '4px' }}
          >
            <Input
              style={{ borderRadius: '6px', border: '1px solid #DBDBDC', fontSize: '14px' }}
              placeholder={'请输入名称'}
              disabled
            />
          </Form.Item>
          <Form.Item
            className="form-icon-color"
            label="接口地址"
            name="fullName"
            style={{ marginTop: '4px' }}
          >
            <Input
              style={{ borderRadius: '6px', border: '1px solid #DBDBDC', fontSize: '14px' }}
              placeholder={'请输入名称'}
              disabled
            />
          </Form.Item>
          <Form.Item
            className="form-icon-color"
            label="数据接口说明"
            name="description"
            style={{ marginTop: '4px' }}
          >
            <Input.TextArea
              style={{ borderRadius: '6px', border: '1px solid #DBDBDC', fontSize: '14px' }}
              placeholder={'请输入'}
            />
          </Form.Item>
          <Form.Item>
            <Form.List name={['properties', 'list']}>
              {(subFields, subOpt) => (
                <div
                  style={{
                    display: 'flex',
                    flexDirection: 'column',
                  }}
                >
                  <Space style={{ padding: '0px 10px' }}>
                    <div style={{ width: '200px' }}>参数名称</div>
                    <div style={{ width: '200px' }}>参数说明</div>
                    <div style={{ width: '100px' }}>参数类型</div>
                    <div style={{ width: '100px' }}>必须：</div>
                  </Space>

                  {subFields && subFields.length > 0 ? (
                    <div
                      ref={scrollContainerRef}
                      style={{
                        maxHeight: '180px',
                        overflowY: 'auto',
                        border: '1px solid #DBDBDC',
                        borderRadius: '6px',
                        scrollbarWidth: 'none',
                        margin: '10px 0px',
                        padding: '10px',
                      }}
                      className="last-buttom"
                    >
                      {subFields.map((subField) => (
                        <div key={subField.key}>
                          <Space
                            key={subField.key}
                            className="icon-lhight"
                            style={{ marginBottom: '10px' }}
                          >
                            <Form.Item
                              name={[subField.name, 'first']}
                              rules={[{ required: true, message: '请输入' }]}
                            >
                              <Input placeholder="请输入" style={{ width: '200px' }} />
                            </Form.Item>
                            <Form.Item
                              name={[subField.name, 'second']}
                              rules={[{ required: true, message: '请输入' }]}
                            >
                              <Input placeholder="请输入" style={{ width: '200px' }} />
                            </Form.Item>

                            <Form.Item name={[subField.name, 'third']}>
                              <Select
                                placeholder="请选择"
                                style={{ width: '100px' }}
                                defaultValue={'string'}
                              >
                                <Select.Option value="string">string</Select.Option>
                                <Select.Option value="integer">integer</Select.Option>
                                <Select.Option value="boolean">boolean</Select.Option>
                                <Select.Option value="number">number</Select.Option>
                                <Select.Option value="array">array</Select.Option>
                                <Select.Option value="object">object</Select.Option>
                              </Select>
                            </Form.Item>

                            <Form.Item name={[subField.name, 'fourth']} style={{ width: '100px' }}>
                              <Select
                                defaultValue="否"
                                style={{ width: 100 }}
                                options={[
                                  { value: '是', label: '是' },
                                  { value: '否', label: '否' },
                                ]}
                                placeholder="请选择"
                              />
                            </Form.Item>

                            <CloseOutlined
                              onClick={() => {
                                subOpt.remove(subField.name);
                              }}
                            />

                          </Space>
                          <div style={{ paddingLeft: '0px', marginBottom: '20px' }}>
                            <Form.Item
                              name={[subField.name, 'enum']}
                              style={{ marginBottom: '0px' }}
                            >
                              <TagInput
                                className=""
                                defaultTags={onItem?.properties?.list?.[subField.name]?.fifth}
                                placeholder="输入示例值，并按回车"
                                minRows={1}
                                warningMessage="示例值已存在"
                                onChange={(tags) => {
                                  const values = form.getFieldsValue();
                                  const list = values.properties.list;
                                  console.log(values)
                                  const currentType = list[subField.name].third;

                                  if ((currentType === 'array' || currentType === 'object') && tags.length > 0) {
                                    message.warning('array 和 object 类型不支持示例值配置');
                                    return;
                                  }

                                  const validTags: any[] = [];
                                  let hasInvalidValue = false;

                                  tags.forEach(tag => {
                                    const { isValid, convertedValue } = validateAndConvertValue(currentType, String(tag));
                                    if (isValid) {
                                      validTags.push(convertedValue);
                                    } else {
                                      hasInvalidValue = true;
                                    }
                                  });

                                  if (hasInvalidValue) {
                                    message.warning(`请输入有效的 ${currentType} 类型值`);
                                    return;
                                  }

                                  list[subField.name].fifth = validTags;
                                  form.setFieldsValue({
                                    properties: {
                                      list
                                    }
                                  });
                                }}
                              />
                            </Form.Item>
                          </div>
                        </div>
                      ))}
                    </div>
                  ) : (
                    <div
                      ref={scrollContainerRef}
                      style={{
                        maxHeight: '180px',
                        overflowY: 'auto',
                        border: '1px solid #DBDBDC',
                        borderRadius: '6px',
                        scrollbarWidth: 'none',
                        margin: '10px 0px',
                        padding: '10px',
                        textAlign: 'center',
                      }}
                      className="last-buttom"
                    >
                      暂无参数
                    </div>
                  )}

                  <Button type="dashed" onClick={() => handleAdd(subOpt)} block>
                    + 添加参数
                  </Button>
                </div>
              )}
            </Form.List>
          </Form.Item>
        </Form>
      </div>
    </Modals>
  );
};

export default connectorAddModal;
